package server.game.world.item;

import java.util.*;
import server.Main;
import server.game.entity.GroundItem;
import server.game.entity.character.player.Player;

public class GroundItemManager {
	
	private ArrayList<GroundItem> groundItemList = new ArrayList<GroundItem>(500);

	public void processGlobalItemTimers() {
		HashSet<GroundItem> toRemove = new HashSet<GroundItem>();
		for(GroundItem groundItem : groundItemList) {
			if(groundItem == null) continue;
			groundItem.decrementTimer();
			if(groundItem.getTimer() <= 0) {
				if(groundItem.isPublic()) { //TODO: OR UNTRADABLE
					toRemove.add(groundItem);
					deleteGroundItem(groundItem, false);
				} else {
					groundItem.setTimer(30);
					groundItem.delete(groundItem.getOwner());
					groundItem.setPublic(true);
					for(Player player : Main.getWorld().getPlayers()) {
						if(player == null) continue;
						groundItem.put(player);
					}
				}
			}
		}
		groundItemList.removeAll(toRemove);
	}

	public GroundItem getGroundItem(int id, int x, int y, int z) {
		for(GroundItem groundItem : groundItemList) {
			if(groundItem == null) continue;
			if(groundItem.getX() == x && groundItem.getY() == y && groundItem.getId() == id && groundItem.getZ() == z) {
				return groundItem;
			}
		}
		return null;
	}

	public void dropGlobalItem(int itemId, int itemAmt, int x, int y, int z) {
		GroundItem groundItem = new GroundItem(itemId, itemAmt, x, y, z);
		groundItemList.add(groundItem);
		for(Player player : Main.getWorld().getPlayers()) {
			if(player == null) continue;
			groundItem.put(player);
		}
	}

	public void dropItem(Player p, int itemId, int itemAmt, int x, int y, int z) {
		GroundItem groundItem = new GroundItem(p, itemId, itemAmt, x, y, z);
		groundItemList.add(groundItem);
		groundItem.put(p);
	}

	public void deleteGroundItem(GroundItem groundItem, boolean deleteFromList) {
		for(Player player : Main.getWorld().getPlayers()) {
			if(player == null) continue;
			groundItem.delete(player);
		}
		if(deleteFromList) {
			groundItemList.remove(groundItem);
		}
	}
}
